<?php
namespace app\common\model\system;


use app\common\model\TimeModel;
use think\facade\Session;

class SystemAuth extends TimeModel
{
    protected $deleteTime = 'delete_time';

    /**
     * 根据角色ID获取授权节点
     * @param $authId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAuthorizeNodeListByAdminId($authId)
    {

        $checkNodeList = (new SystemAuthNode())
            ->where('auth_id', $authId)
            ->column('node_id');
        $user = Session::get('admin');
        $auth = $user['auth_ids'];
        //dump($where);
        $SystemMenu = app('app\common\model\system\SystemMenu');
        if($auth !=0){//如果非超级管理员
            $node_ids = SystemAuthNode::where('auth_id',$auth)->column('node_id');
            $nodelList = $SystemMenu
                ->whereIn('id',$node_ids)
                ->field('id,path,pid as pId,title as name,type')
                ->select()
                ->toArray();
        }else{
            $nodelList = $SystemMenu
                ->field('id,path,pid as pId,title as name,type')
                ->select()
                ->toArray();
        }




        $newNodeList = [];
        foreach ($nodelList as $vo) {

                $vo = array_merge($vo, ['field' => 'href', 'spread' => true]);
                $vo['isCheck'] =in_array($vo['id'], $checkNodeList) ? true : true;
                $vo['open'] = true;
                //$vo['title'] = "{$vo['name']}【{$vo['field']}】";
                $children = [];
                foreach ($nodelList as $v) {
                    if ($v['type'] == 2 && strpos($v['name'], $vo['path'] . '/') !== false) {
                        $v = array_merge($v, ['field' => 'node', 'spread' => true]);
                        $v['isCheck'] = in_array($v['id'], $checkNodeList) ? true : true;
                        $v['title'] = "{$v['name']}【{$v['href']}】";

                        $children[] = $v;

                    }
                }
                !empty($children) && $vo['children'] = $children;
                $newNodeList[] = $vo;

        }

        return $newNodeList;
    }

    /**
     * 定义全局的查询范围
     * @param \think\db\Query $query
     */
    public function scopeApp_id($query)
    {
        return true;
    }
}